package controller

import (
	"doctor_api_backend/config"
	model "doctor_api_backend/models"
	"net/http"

	"github.com/gin-gonic/gin"
)

// 没有人在乎id，全都是找药品中其他唯一标识字段

// 获取所有药品
func GetMedicines(c *gin.Context) {
	var medicines []model.Medicine
	err := config.DB.Find(&medicines).Error
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取药品失败"})
		return
	}
	c.JSON(http.StatusOK, medicines)
}

// 通过medicine_code获取单个药品
func GetMedicine(c *gin.Context) {
	medicineCode := c.Param("medicineCode")

	var medicine model.Medicine
	err := config.DB.Where("medicine_code = ?", medicineCode).First(&medicine).Error
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "药品不存在"})
		return
	}
	c.JSON(http.StatusOK, medicine)
}

// 创建药品
func CreateMedicine(c *gin.Context) {
	var medicine model.Medicine
	if err := c.ShouldBindJSON(&medicine); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	err := config.DB.Create(&medicine).Error
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "创建药品失败"})
		return
	}
	c.JSON(http.StatusOK, medicine)
}

// 通过medicine_code更新药品
func UpdateMedicine(c *gin.Context) {
	medicineCode := c.Param("medicineCode")
	var medicine model.Medicine
	if err := config.DB.Where("medicine_code = ?", medicineCode).First(&medicine).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "药品不存在"})
		return
	}
	if err := c.ShouldBindJSON(&medicine); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	err := config.DB.Save(&medicine).Error
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "更新药品失败"})
		return
	}
	c.JSON(http.StatusOK, medicine)
}

// 通过medicine_code删除药品
func DeleteMedicine(c *gin.Context) {
	medicineCode := c.Param("medicineCode")
	var medicine model.Medicine
	if err := config.DB.Where("medicine_code = ?", medicineCode).Delete(&medicine).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "删除药品失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "药品删除成功"})
}
